package com.business.business.support.utils.requestutil;

import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

/**
 * HttpRequest格式转换工具类
 * Created by xuanguangyao on 2018/11/6.
 */
public class HttpRequestUtil {

    /**
     * 通用请求格式转换：可以支持json和form-data两种传参方式
     * @param httpServletRequest
     * @return
     */
    public static cn.hutool.json.JSONObject commonHttpRequestParamConvert(HttpServletRequest httpServletRequest) {
        cn.hutool.json.JSONObject params = new cn.hutool.json.JSONObject();
        try {
            Map<String, String[]> requestParams = httpServletRequest.getParameterMap();
            if (requestParams != null && !requestParams.isEmpty()) {
                requestParams.forEach((key, value) -> params.put(key, value[0]));
            } else {
                StringBuilder paramSb = new StringBuilder();
                try {
                    String str = "";
                    BufferedReader br = httpServletRequest.getReader();
                    while((str = br.readLine()) != null){
                        paramSb.append(str);
                    }
                } catch (Exception e) {
                    System.out.println("httpServletRequest get requestbody error, cause : " + e);
                }
                if (paramSb.length() > 0) {
                    JSONObject paramJsonObject = JSON.parseObject(paramSb.toString());
                    if (paramJsonObject != null && !paramJsonObject.isEmpty()) {
                        paramJsonObject.forEach((key, value) -> params.put(key, String.valueOf(value)));
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("commonHttpRequestParamConvert error, cause : " + e);
        }
        return params;
    }
    /**
     * 微信支付回调地址用
     * @param httpServletRequest
     * @return
     */
    public static Map<String,Object> commonHttpRequestParamConvert2(HttpServletRequest httpServletRequest) throws IOException {
        StringBuilder sb = new StringBuilder();
        String inputLine;
        while ((inputLine = httpServletRequest.getReader().readLine()) != null) {
            sb.append(inputLine);
        }
        httpServletRequest.getReader().close();
        String jsonStr = JSON.toJSONString(sb.toString()).replace("<![CDATA[", "").replace("]]>", "").replace("\"", "");
        Map<String,Object> map = XmlUtil.xmlToMap(jsonStr);
        return map;
    }
}
